package com.fjnu.aspect;


import com.fjnu.annotation.PerformanceMonitor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Component
@Aspect
@Slf4j
public class PerformanceMonitorAspect {


    /**
     * pointcut 定义
     */
    @Pointcut("@annotation(performanceMonitor)")
    public void keyQueryMethod(PerformanceMonitor performanceMonitor) {}

    @Pointcut("@within(performanceMonitor)")
    public void methodsInUserDao(PerformanceMonitor performanceMonitor){}
    /**
     * advice
     */
    @Around("keyQueryMethod(performanceMonitor) || methodsInUserDao(performanceMonitor)")
    public Object performanceMonitorAdvice(ProceedingJoinPoint joinPoint,
                                           PerformanceMonitor performanceMonitor) throws Throwable {

        long alarmedTime = performanceMonitor.alarmedTime();
        long startTime = System.currentTimeMillis();
        log.info(" [KeyQueryMethodAroundAdvice] method {} matched.", joinPoint.getSignature().getName());
        Object result = joinPoint.proceed();
        long endTime = System.currentTimeMillis();
        if (endTime - startTime > alarmedTime) {
            log.warn(" [KeyQueryMethodAroundAdvice] method {} takes {} ms, which is longer than {} ms",
                    joinPoint.getSignature().getName(), endTime - startTime, alarmedTime);
        }

        return result ;
    }


}
